//
//  DeviceListViewController.m
//  IPTV
//
//  Created by Echo on 14-4-2.
//  Copyright (c) 2014年 Echo. All rights reserved.
//

#import "DeviceListViewController.h"
//#import "TVViewController.h"
#import "PokerControlClient.h"
#import "RemoteControlClient.h"
#import "DDAlertPrompt.h"
#import "NewWifiViewController.h"
#import "DeviceInfoViewController.h"

@interface DeviceListViewController (){
    NSMutableDictionary *array;
    
    int sendCount;
    NSTimer *timer;
}

@end

@implementation DeviceListViewController
@synthesize TableView1, udpSocket, version_;


-(unsigned int)getInt:(NSString*)nextstr{
    unsigned int tempf;
    NSString *mutString = [nextstr substringFromIndex:2];
    NSString *str1 = [mutString substringFromIndex:4];
    NSString *str2 = [mutString substringToIndex:4];
    NSString *string1 = [NSString stringWithFormat:@"%@%@", str1, str2];
    NSScanner *scanner = [NSScanner scannerWithString:string1];
    [scanner scanHexInt: &tempf];
    return tempf;
    //    label.text = [NSString stringWithFormat:@"%d.0", tempf];
}


-(float)getFloat:(NSString*)nextstr{
    unsigned tempi;
    NSString *mutString = [nextstr substringFromIndex:2];
    NSString *str1 = [mutString substringFromIndex:4];
    NSString *str2 = [mutString substringToIndex:4];
    NSString *string1 = [NSString stringWithFormat:@"%@%@", str1, str2];
    NSScanner *scanner = [NSScanner scannerWithString:string1];
    [scanner scanHexInt:&tempi];
    float *tempf = (float *)&tempi;
    return *tempf;
}


-(NSString *)stringFromHexStringxx:(NSString *)hexString { //
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    return unicodeString;
}
-(NSString* )getStringxx:(NSString*)nextstr{
    NSString *mutString = [nextstr substringFromIndex:2];
    return [self stringFromHexStringxx:mutString];
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        [NC addObserver:self selector:@selector(getSocketData:) name:GET_SEARCH_SOCKET_UdpData object:nil];
        array = [[NSMutableDictionary alloc] init];
        [NC addObserver:self selector:@selector(resignActive) name:NOTI_RESIGN_ACTIVE object:nil];
        [NC addObserver:self selector:@selector(becomeActive) name:NOTI_BECOME_ACTIVE object:nil];
        // Custom initialization
        //版本  瞬时流量  累计量
        sendCount = 0;
        
    }
    return self;
}
- (void)getSocketData:(NSNotification*)noti{
    NSDictionary *fasda = noti.object;
    if (fasda.count > 0) {
        NSString *name = [[fasda allKeys] objectAtIndex:0];
        [array setObject:name forKey:name];
    }
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(beginRemoveAllDevice) object:nil];
    [TableView1 reloadData];
}
- (void)beginRemoveAllDevice{
    NSLog(@"移除所有的设备 ");
    [array removeAllObjects];
    [TableView1 reloadData];
}
-(void)stopUdpData{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(beginRemoveAllDevice) object:nil];
    //    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendUdpData) object:nil];
    [timer invalidate]; timer = nil;
    NSLog(@"停止发送udp包");
    self.udpSocket = nil;
    isStopUdpData = YES;
    [activityView stopAnimating];
}
- (void)resignActive{
    [self stopUdpData];
}
- (void)becomeActive{
    [self performSelector:@selector(beginSearchDevice) withObject:nil afterDelay:1];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [dicList setDictionary:[UD objectForKey:LANIPAddress_list]];
    [TableView1 reloadData];
    
    if (dicList.count > 0) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(beginRemoveAllDevice) object:nil];
        [self beginSearchDevice];
    }
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopUdpData];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
//SearchINFO1030876323530313133360406513F9E0419330000
//107 046D332F68 087632353031313336 0406513F9E 0406513F9E 0406513F9E 0419330000 020003
-(void)sendUdpData{
    if (!isStopUdpData) {
        int port = 15003;
        if (!self.udpSocket) {
            self.udpSocket = [[AsyncUdpSocket alloc] initWithDelegate:self];
            NSError *error = nil;
            [self.udpSocket enableBroadcast:YES error:&error];
            if (![self.udpSocket bindToPort:port error:&error]){
                NSLog(@"bindToPort error");
                return;
            }
        }
        //030876323530313133360406513F9E0419330000
        //1030876323530313133360406513F9E0419330000
        [self.udpSocket receiveWithTimeout:-1 tag:0];
        NSString *sentip = @"255.255.255.255";
        NSString *dataStr = @"INFOProbeDevice030045000400040002000E0002";
        dataStr = @"INFOSearchDevice030045000400040002000E0002";
        dataStr = send_str;
        NSData *data = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"SEND TO : %@: %d    %@", sentip, port, dataStr);
        
        [self.udpSocket sendData:data toHost:sentip port:port withTimeout:-1 tag:0];
        //        [self performSelector:@selector(sendUdpData) withObject:nil afterDelay:3];
        int count = 4;
        sendCount++;
        if (sendCount%count == 0) {
            self.udpSocket = nil;
            //            [self beginRemoveAllDevice];
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(beginRemoveAllDevice) object:nil];
            [self performSelector:@selector(beginRemoveAllDevice) withObject:nil afterDelay:timer_time*count-1];
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
    
    //107046D332F680876323530313133360406513F9E0406513F9E0406513F9E0419330000020003
    
//        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
//        [dic setObject:@"10.10.10.25" forKey:@"107046D332F680836323530313133360406513F9E0406513F9E0406513E9E0417330000020003"];
//        [dic setObject:@"10.10.10.250" forKey:@"107046D332F680876323530313133360406513F9E0406513F9E0406513F9E0419330000020003"];
//        [dic setObject:@"192.168.1.116" forKey:@"107046D332F680846323530313133360406513F9E0406513F9E0406513D9E0418330000020003"];
////        [dic setObject:@"192.168.1.117" forKey:@"107046D332F680876323530313133360406513F9E0406513F9E0406513F9E0419330000020002"];
//        [UD setObject:dic forKey:LANIPAddress_list];
//        [UD synchronize];
    //
    netConnectSucList = [[NSMutableArray alloc] init];
    dicList = [[NSMutableDictionary alloc] init];
    [dicList setDictionary:[UD objectForKey:LANIPAddress_list]];
    //    [UD removeObjectForKey:LANIPAddress_list];
    //    [UD synchronize];
    
    self.TableView1 = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    self.TableView1.backgroundColor = [UIColor whiteColor];
    self.TableView1.delegate = self;
    self.TableView1.dataSource = self;
    self.TableView1.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.TableView1];
    
    UIImageView *img = [[UIImageView alloc] initWithImage:IMG(@"home_bg.png")];
    img.userInteractionEnabled = YES;
    img.frame = CGRectMake(0, 0, SCREEN_WIDTH, 170);
    self.TableView1.tableHeaderView = img;
    
    
    //    [[PokerControlClient share].curIpList removeAllObjects];
    //    [NC addObserver:self selector:@selector(connectWIFI) name:StopUdpData object:nil];
    //    [self performSelector:@selector(connectDeviceList) withObject:nil afterDelay:1];
    
    isStopUdpData = YES;
    
    //GET_SOCKET_UdpData
    
    //    if (dicList.count > 0) {
    //        [self beginSearchDevice];
    //    }
    
    UIView *headview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    for (int i=0; i<2; i++) {
        GoodBtn *btn = [GoodBtn btnWithFont:20];
        btn.frame = CGRectMake(35, 0, SCREEN_WIDTH-35*2, 64);
        btn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
        [btn setTitle:@"仪表列表" forState:UIControlStateNormal];
        [btn setTitleColor:RGB(255, 255, 255, 1) forState:UIControlStateNormal];
        if (i == 1) {
            btn.frame = CGRectMake(FX(btn)+150, FY(btn), 100, 64);
            //            [btn setTitle:@"扫瞄" forState:UIControlStateNormal];
            [btn setTitle:@"" forState:UIControlStateNormal];
            
            //            activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
            //
            //            [btn addSubview:activityView];
            //            activityView.frame = CGRectMake(80, (FH(btn)-25)/2, 25, 25);
            
            [btn addTarget:self action:@selector(btnxxxPressed) forControlEvents:UIControlEventTouchUpInside];
        }
        [btn setBackgroundImage:IMG(@"TabBarBtn.png") forState:UIControlStateHighlighted];
        [headview addSubview:btn];
    }
    //    self.TableView1.tableHeaderView = headview;
    
    //    UIView *footview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    UIButton *button = [[UIButton alloc] init];
    [button addTarget:self action:@selector(buttonPressed) forControlEvents:UIControlEventTouchUpInside];
    button.frame = CGRectMake(SCREEN_WIDTH-85, FH(img)-50, 50, 50);
    [button setImage:IMG(@"new_device.png") forState:UIControlStateNormal];
    [img addSubview:button];
    
    UIImageView *logo = [[UIImageView alloc] initWithImage:IMG(@"tubiao.png")];
    logo.frame = CGRectMake(30, FH(img)-FH(logo)*0.85, FW(logo)*0.85, FH(logo)*0.85);
    [img addSubview:logo];
    //    self.TableView1.tableFooterView = footview;
}
-(void)beginSearchDevice{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(beginSearchDevice) object:nil];
    isStopUdpData = NO;
    //    [self sendUdpData];
    if (!timer) {
        [self sendUdpData];
        timer = [NSTimer scheduledTimerWithTimeInterval:timer_time
                                                 target:self
                                               selector:@selector(sendUdpData)
                                               userInfo:nil
                                                repeats:YES];
    }
    [activityView startAnimating];
}
-(void)btnxxxPressed{
    //    if (isStopUdpData) {
    //        [self beginSearchDevice];
    //    }else{
    //        NSLog(@"停止扫描");
    //        [self stopUdpData];
    //    }
}
-(void)buttonPressed{
    NewDeviceViewController *newDeviceView = [[NewDeviceViewController alloc] init];
    [self.navigationController pushViewController:newDeviceView animated:YES];
}
-(void)connectDeviceList{
    if ([PokerControlClient share].curIpList.count == 0) {
        if (dicList.count > 0){
            [NC addObserver:self selector:@selector(remoteNetConnectSuc) name:CONNECT_SUC_REMOTE object:nil];
            [[RemoteControlClient share] openStream];
        }
    }
}
-(void)connectWIFI{
    [dicList setDictionary:[UD objectForKey:LANIPAddress_list]];
    m_isRemote = NO;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(connectDeviceList) object:nil];
    [TableView1 reloadData];
}
-(void)remoteDeviceName:(NSNotification*)noti{
    NSLog(@"remoteDeviceName : %@", noti.object);
    //    [NC removeObserver:self name:StopUdpData object:nil];
    //    [self stopUdpData];
    NSString *str = noti.object;
    [netConnectSucList addObject:str];
    m_isRemote = YES;
    [TableView1 reloadData];
}
-(void)remoteNetConnectSuc{
    [NC addObserver:self selector:@selector(remoteDeviceName:) name:REMOTE_DEVICE_NAME object:nil];
    for (int i=0; i<[dicList allKeys].count; i++) {
        NSString *name = [[dicList allKeys] objectAtIndex:i];//0026290305a2
        NSString *string = [NSString stringWithFormat:@"[%@]", name];
        NSLog(@"stringname : %@", string);
        [[RemoteControlClient share] startRemoteCmd:0x10 sec:0x03 dataStr:string];//获取设备是否在线
    }
}
-(void)dealloc{
    NSLog(@"");
    [[RemoteControlClient share] disConnect];
    [NC removeObserver:self];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dicList.count/2+(dicList.count%2>0?1:0);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return cell_height+13;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    cell.backgroundColor = [UIColor grayColor];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"TableView1Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, cell_height+13-2+1.5)];
    bg.backgroundColor = [UIColor whiteColor];
    [cell addSubview:bg];
    
    UIButton *viewbg = [[UIButton alloc] initWithFrame:CGRectMake(30, 8+13, SCREEN_WIDTH-110*2+15, cell_height-40)];
    [viewbg setBackgroundImage:IMG(@"bg_btn_gray.png") forState:UIControlStateNormal];
    viewbg.clipsToBounds = NO;
    viewbg.hidden = YES;
//    viewbg.layer.masksToBounds = YES;
//    viewbg.layer.cornerRadius = 10;
    [cell addSubview:viewbg];
//    viewbg.backgroundColor = [UIColor grayColor];
    
    NSLog(@"viewbg %@ %d", viewbg, indexPath.row);
    
    
    
    GoodLabel *nameLabel = [GoodLabel labelWithFont:20 title:STR(@"")];
    nameLabel.adjustsFontSizeToFitWidth = YES;
    nameLabel.textAlignment = UITextAlignmentCenter;
    nameLabel.text = STR(@"");
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.frame = CGRectMake(0, 12, FW(viewbg), 20);
    [viewbg addSubview:nameLabel];
    
    UIButton *viewbg1 = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-FW(viewbg)-FX(viewbg), FY(viewbg), FW(viewbg), FH(viewbg))];
    [viewbg1 setBackgroundImage:IMG(@"bg_btn_gray.png") forState:UIControlStateNormal];
    viewbg1.clipsToBounds = NO;
    viewbg1.hidden = YES;
    
     NSLog(@"viewbg1 %@ %d", viewbg1, indexPath.row);
//    viewbg1.backgroundColor = [UIColor grayColor];
//    viewbg1.layer.masksToBounds = YES;
//    viewbg1.layer.cornerRadius = 10;
    [cell addSubview:viewbg1];
    
    GoodLabel *nameLabel1 = [GoodLabel labelWithFont:20 title:STR(@"")];
    nameLabel1.adjustsFontSizeToFitWidth = YES;
    nameLabel1.textAlignment = UITextAlignmentCenter;
    nameLabel1.text = STR(@"");
    nameLabel1.textColor = [UIColor whiteColor];
    nameLabel1.frame = CGRectMake(0, 12, FW(viewbg), 20);
    [viewbg1 addSubview:nameLabel1];
    //107046D332F680876323530313133360406513F9E0406513F9E0406513F9E0419330000020003
    
    NSString *device_name_next = nil;//1
    if ([dicList allKeys].count > indexPath.row*2) {
        
        viewbg.hidden = NO;
        NSString *device_name = nil;//1
        device_name = [[dicList allKeys] objectAtIndex:indexPath.row*2];
        
        device_name_next = device_name;
        NSLog(@"device_name %@ %d", device_name, indexPath.row);
        
        GoodLabel *deviceLabel = [GoodLabel labelWithFont:17 title:[device_name substringFromIndex:1]];
        deviceLabel.adjustsFontSizeToFitWidth = YES;
        deviceLabel.textAlignment = UITextAlignmentCenter;
        deviceLabel.textColor = nameLabel.textColor;
        deviceLabel.frame = CGRectMake(0, 39, FW(viewbg), 20);
        [viewbg addSubview:deviceLabel];
        
        NSDictionary *dicNameList = [UD objectForKey:LAN_Remote_Name_list];
        NSString *UserDeviceName = [dicNameList objectForKey:device_name];
        if ([UserDeviceName length] > 0) {
            nameLabel.text = UserDeviceName;
        }
        //版本  瞬时流量  累计量
        
        
        NSString *string = [[device_name substringFromIndex:1] substringFromIndex:2];
        NSString *num1 = [string substringToIndex:2];
        NSString *stringsub1 = [string substringToIndex:2+[num1 intValue]*2];
        NSString *getstring1 = [self getStringxx:stringsub1];//瞬时流量的单位string1
        
        string = [string substringFromIndex:2+[num1 intValue]*2];
        NSString *num2 = [string substringToIndex:2];
        NSString *stringsub2 = [string substringToIndex:2+[num2 intValue]*2];
        NSString *getstring2 = [self getStringxx:stringsub2];//仪表序列号string2
        
        string = [string substringFromIndex:2+[num2 intValue]*2];
        NSString *num3 = [string substringToIndex:2];
        NSString *stringsub3 = [string substringToIndex:2+[num3 intValue]*2];
        stringsub3 = [string substringToIndex:2+[num3 intValue]*2];
        float getfloat1 = [self getFloat:stringsub3];//瞬时流量/秒real3
        
        string = [string substringFromIndex:2+[num3 intValue]*2];
        NSString *num4 = [string substringToIndex:2];
        NSString *stringsub4 = [string substringToIndex:2+[num4 intValue]*2];
        stringsub4 = [string substringToIndex:2+[num4 intValue]*2];
        float getfloat2 = [self getFloat:stringsub4];//瞬时流量/秒real4
        
        string = [string substringFromIndex:2+[num4 intValue]*2];
        NSString *num5 = [string substringToIndex:2];
        NSString *stringsub5 = [string substringToIndex:2+[num5 intValue]*2];
        stringsub5 = [string substringToIndex:2+[num5 intValue]*2];
        float getfloat3 = [self getFloat:stringsub5];//瞬时流量/秒real5
        
        string = [string substringFromIndex:2+[num5 intValue]*2];
        NSString *num6 = [string substringToIndex:2];
        NSString *stringsub6 = [string substringToIndex:2+[num6 intValue]*2];
        stringsub6 = [string substringToIndex:2+[num6 intValue]*2];
        unsigned int getint1 = [self getInt:stringsub6];//净累积量int1
        
        string = [string substringFromIndex:2+[num6 intValue]*2];
        NSString *num7 = [string substringToIndex:2];
        NSString *stringsub7 = [string substringToIndex:2+[num7 intValue]*2];
        stringsub7 = [string substringToIndex:2+[num7 intValue]*2];
        //        unsigned int getint2 = [self getIntyy:stringsub7];//净累积量指数int2
        
        
        GoodLabel *visionLabel = [GoodLabel labelWithFont:14 title:STR(@"")];
        visionLabel.tag = 5555;
        visionLabel.textAlignment = UITextAlignmentCenter;
        visionLabel.textColor = viewbg.backgroundColor;
        visionLabel.frame = CGRectMake(0, FH(viewbg)+3, FW(viewbg), 20);
        [viewbg addSubview:visionLabel];
        
        visionLabel.text = getstring2;
        if ([getstring1 hasSuffix:@"s"]) {
            nameLabel.text = [NSString stringWithFormat:@"%.2f", getfloat1];//瞬时流量
        }else if ([getstring1 hasSuffix:@"m"]) {
            nameLabel.text = [NSString stringWithFormat:@"%.2f", getfloat2];//瞬时流量
        }else{
            nameLabel.text = [NSString stringWithFormat:@"%.2f", getfloat3];//瞬时流量
        }
        
        deviceLabel.text = [NSString stringWithFormat:@"%d×%@", getint1, [RecInfo getInt:stringsub7]];
        
    }
    if ([dicList allKeys].count > indexPath.row*2+1) {
        
        
        viewbg1.hidden = NO;
        
        NSString *device_name1 = [[dicList allKeys] objectAtIndex:indexPath.row*2+1];
        
        NSLog(@"device_namexxxx %@ %d", device_name1, indexPath.row);
        
        GoodLabel *deviceLabel1 = [GoodLabel labelWithFont:17 title:[device_name1 substringFromIndex:1]];
        deviceLabel1.adjustsFontSizeToFitWidth = YES;
        deviceLabel1.textAlignment = UITextAlignmentCenter;
        deviceLabel1.textColor = nameLabel1.textColor;
        deviceLabel1.frame = CGRectMake(0, 39, FW(viewbg), 20);
        [viewbg1 addSubview:deviceLabel1];
        
        NSDictionary *dicNameList = [UD objectForKey:LAN_Remote_Name_list];
        NSString *UserDeviceName = [dicNameList objectForKey:device_name1];
        if ([UserDeviceName length] > 0) {
            nameLabel1.text = UserDeviceName;
        }
        //版本  瞬时流量  累计量
        

         NSString *string = [[device_name1 substringFromIndex:1] substringFromIndex:2];
         NSString *num1 = [string substringToIndex:2];
         NSString *stringsub1 = [string substringToIndex:2+[num1 intValue]*2];
         NSString *getstring1 = [self getStringxx:stringsub1];//瞬时流量的单位string1
         
         string = [string substringFromIndex:2+[num1 intValue]*2];
         NSString *num2 = [string substringToIndex:2];
         NSString *stringsub2 = [string substringToIndex:2+[num2 intValue]*2];
         NSString *getstring2 = [self getStringxx:stringsub2];//仪表序列号string2
         
         string = [string substringFromIndex:2+[num2 intValue]*2];
         NSString *num3 = [string substringToIndex:2];
         NSString *stringsub3 = [string substringToIndex:2+[num3 intValue]*2];
         stringsub3 = [string substringToIndex:2+[num3 intValue]*2];
         float getfloat1 = [self getFloat:stringsub3];//瞬时流量/秒real3
         
         string = [string substringFromIndex:2+[num3 intValue]*2];
         NSString *num4 = [string substringToIndex:2];
         NSString *stringsub4 = [string substringToIndex:2+[num4 intValue]*2];
         stringsub4 = [string substringToIndex:2+[num4 intValue]*2];
         float getfloat2 = [self getFloat:stringsub4];//瞬时流量/秒real4
         
         string = [string substringFromIndex:2+[num4 intValue]*2];
         NSString *num5 = [string substringToIndex:2];
         NSString *stringsub5 = [string substringToIndex:2+[num5 intValue]*2];
         stringsub5 = [string substringToIndex:2+[num5 intValue]*2];
         float getfloat3 = [self getFloat:stringsub5];//瞬时流量/秒real5
         
         string = [string substringFromIndex:2+[num5 intValue]*2];
         NSString *num6 = [string substringToIndex:2];
         NSString *stringsub6 = [string substringToIndex:2+[num6 intValue]*2];
         stringsub6 = [string substringToIndex:2+[num6 intValue]*2];
         unsigned int getint1 = [self getInt:stringsub6];//净累积量int1
         
         string = [string substringFromIndex:2+[num6 intValue]*2];
         NSString *num7 = [string substringToIndex:2];
         NSString *stringsub7 = [string substringToIndex:2+[num7 intValue]*2];
         stringsub7 = [string substringToIndex:2+[num7 intValue]*2];
         //        unsigned int getint2 = [self getIntyy:stringsub7];//净累积量指数int2
         
         
         GoodLabel *visionLabel = [GoodLabel labelWithFont:14 title:STR(@"")];
         visionLabel.tag = 5555;
         visionLabel.textAlignment = UITextAlignmentCenter;
         visionLabel.textColor = viewbg.backgroundColor;
        visionLabel.frame = CGRectMake(0, FH(viewbg1)+3, FW(viewbg1), 20);
        [viewbg1 addSubview:visionLabel];
         
         visionLabel.text = getstring2;
         if ([getstring1 hasSuffix:@"s"]) {
         nameLabel1.text = [NSString stringWithFormat:@"%.2f", getfloat1];//瞬时流量
         }else if ([getstring1 hasSuffix:@"m"]) {
         nameLabel1.text = [NSString stringWithFormat:@"%.2f", getfloat2];//瞬时流量
         }else{
         nameLabel1.text = [NSString stringWithFormat:@"%.2f", getfloat3];//瞬时流量
         }
         
         deviceLabel1.text = [NSString stringWithFormat:@"%d×%@", getint1, [RecInfo getInt:stringsub7]];
        
    }
    
//    UIImage *stateImage = IMG(@"offline.png");
//    
//    if ([Global curLanguageEn]) {
//        stateImage = IMG(@"offline_en.png");
//    }
//
    
    if (dicList.count > indexPath.row*2) {
        viewbg.tag = indexPath.row*2;
        
        NSString *curDevice = [[dicList allKeys] objectAtIndex:indexPath.row*2];
        for (NSString *savaDevice in [array allKeys]) {
            if ([savaDevice isEqualToString:curDevice]) {
//                viewbg.backgroundColor = RGB(0, 105, 235, 1);
                [viewbg setBackgroundImage:IMG(@"bg_btn_blue.png") forState:UIControlStateNormal];
                [viewbg addTarget:self action:@selector(viewbgPressed:) forControlEvents:UIControlEventTouchUpInside];
                break;
            }
        }
    }
    if (dicList.count > indexPath.row*2+1) {
        
        viewbg1.tag = indexPath.row*2+1;
        
        NSString *curDevice = [[dicList allKeys] objectAtIndex:indexPath.row*2+1];
        for (NSString *savaDevice in [array allKeys]) {
            if ([savaDevice isEqualToString:curDevice]) {
//                viewbg1.backgroundColor = RGB(0, 105, 235, 1);
                [viewbg1 setBackgroundImage:IMG(@"bg_btn_blue.png") forState:UIControlStateNormal];
                [viewbg1 addTarget:self action:@selector(viewbgPressed1:) forControlEvents:UIControlEventTouchUpInside];
                break;
            }
        }
    }
    
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
    longPress.minimumPressDuration = 0.8; //定义按的时间
    [viewbg addGestureRecognizer:longPress];
    
    longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(btnLong:)];
    longPress.minimumPressDuration = 0.8; //定义按的时间
    [viewbg1 addGestureRecognizer:longPress];
    
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
- (void)viewbgPressed:(UIButton*)btn{
    if (dicList.count > btn.tag) {
        
        NSString *selectDevice = [[dicList allKeys] objectAtIndex:btn.tag];
        NSString *selectIP = [[dicList allValues] objectAtIndex:btn.tag];
        
        for (int i=0; i<[array allKeys].count; i++) {
            
            NSString *searchDevice = [[array allKeys] objectAtIndex:i];
            if ([searchDevice isEqualToString:selectDevice]) {
                
                [PokerControlClient share].ctrlIP = selectIP;
                [[PokerControlClient share] stopc2sPing];
                
                NSLog(@"DeviceListViewController  %@", version_);
                
                UILabel *visionLabel = (UILabel *)[btn viewWithTag:5555];
                DeviceInfoViewController *newDeviceView = [[DeviceInfoViewController alloc] init];
                newDeviceView.version_ = visionLabel.text;
                [self.navigationController pushViewController:newDeviceView animated:YES];
                
                break;
            }
        }
    }
}
-(void)btnLong:(UILongPressGestureRecognizer *)gestureRecognizer{
    UIView *view = gestureRecognizer.view;
    delete_index = view.tag;
    
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) {
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否删除吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"删除", nil];
        alert.tag = 8889;
        [alert show];
    }
}
- (void)viewbgPressed1:(UIButton*)btn{
    if (dicList.count > btn.tag) {
        
        NSString *selectDevice = [[dicList allKeys] objectAtIndex:btn.tag];
        NSString *selectIP = [[dicList allValues] objectAtIndex:btn.tag];
        
        for (int i=0; i<[array allKeys].count; i++) {
            NSString *searchDevice = [[array allKeys] objectAtIndex:i];
            if ([searchDevice isEqualToString:selectDevice]) {
                [PokerControlClient share].ctrlIP = selectIP;
                
                [[PokerControlClient share] stopc2sPing];
                
                NSLog(@"DeviceListViewController  %@", version_);
                UILabel *visionLabel = (UILabel *)[btn viewWithTag:5555];
                DeviceInfoViewController *newDeviceView = [[DeviceInfoViewController alloc] init];
                newDeviceView.version_ = visionLabel.text;
                [self.navigationController pushViewController:newDeviceView animated:YES];
                
                break;
            }
        }
    }
}
-(unsigned int )getIntxxxx:(NSString*)nextstr{
    unsigned int tempf;
    NSString *mutString = [nextstr substringFromIndex:2];
    NSString *string1 = mutString;
    NSScanner *scanner = [NSScanner scannerWithString:string1];
    [scanner scanHexInt: &tempf];
    int zhishu = 1;
    for (int i=0;i<tempf;i++) {
        zhishu = 10*zhishu;
    }
    return zhishu;
}
//-(void)setDiveceNameInfo:(NSIndexPath *)indexPath {
//    NSString *device_name = nil;
//    if ([dicList allKeys].count > indexPath.row) {
//        device_name = [[dicList allKeys] objectAtIndex:indexPath.row];
//    }
//    if ([device_name length] > 1) {
//        [PokerControlClient share].net_deviceName = device_name;
//    }
//}
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (dicList.count > 0) {
//        return UITableViewCellEditingStyleDelete;
//    }else {
//        return UITableViewCellEditingStyleNone;
//    }
//}

//#pragma mark -
//#pragma mark Table View Data Source Methods
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSString *device_name = nil;
//    if ([dicList allKeys].count > indexPath.row) {
//        device_name = [[dicList allKeys] objectAtIndex:indexPath.row];
//        [dicList removeObjectForKey:device_name];
//    }
//    [UD setObject:dicList forKey:LANIPAddress_list];
//    [UD synchronize];
//    
//    if ([dicList count] == 0) {
//        [tableView reloadData];
//    } else {
//        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//    }
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    /*
    [PokerControlClient share].isRemote = NO;
    
    [self setDiveceNameInfo:indexPath];
    
    //    m_isRemote = YES;
    //    if (m_isRemote) {
    //        NSString *device_name = nil;
    //        if ([dicList allKeys].count > indexPath.row) {
    //            device_name = [[dicList allKeys] objectAtIndex:indexPath.row];
    //        }
    //        BOOL connect = NO;
    //        for (NSString *name in netConnectSucList) {
    //            if ([name isEqualToString:device_name]) {
    //                connect = YES;
    //                break;
    //            }
    //        }
    ////        connect = YES;
    //        if (connect) {
    //            [PokerControlClient share].isRemote = YES;
    //            [PokerControlClient share].net_deviceName = device_name;
    //            [self enterNextView];
    //        }
    //    }else{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    
    GoodLabel *visionLabel = (GoodLabel*)[cell viewWithTag:5555];
    //        visionLabel.tag = 5555;
    //        visionLabel.textAlignment = UITextAlignmentCenter;
    //        visionLabel.textColor = viewbg.backgroundColor;
    //        visionLabel.frame = CGRectMake(FX(viewbg), cell_height-30, FW(viewbg), 20);
    //        [cell addSubview:visionLabel];
    
    connectIndex = indexPath.row;
    if (dicList.count > indexPath.row) {
        NSString *selectDevice = [[dicList allKeys] objectAtIndex:indexPath.row];
        NSString *selectIP = [[dicList allValues] objectAtIndex:indexPath.row];
        for (int i=0; i<[array allKeys].count; i++) {
            NSString *searchDevice = [[array allKeys] objectAtIndex:i];
            if ([searchDevice isEqualToString:selectDevice]) {
                [PokerControlClient share].ctrlIP = selectIP;
                //                    [self enterNextView];
                
                [[PokerControlClient share] stopc2sPing];
                //    [NC removeObserver:self];
                NSLog(@"DeviceListViewController  %@", version_);
                DeviceInfoViewController *newDeviceView = [[DeviceInfoViewController alloc] init];
                newDeviceView.version_ = visionLabel.text;
                [self.navigationController pushViewController:newDeviceView animated:YES];
                
                break;
            }
        }
    }*/
    //    }
}
-(void)enterNextView{
    [[PokerControlClient share] stopc2sPing];
    //    [NC removeObserver:self];
    NSLog(@"DeviceListViewController  %@", version_);
    DeviceInfoViewController *newDeviceView = [[DeviceInfoViewController alloc] init];
    newDeviceView.version_ = version_;
    [self.navigationController pushViewController:newDeviceView animated:YES];
    
    //    if ([DataManager GetInstance:[PokerControlClient share].net_deviceName].deviceArray.count > 0) {
    //        TVViewController *studyView = [[TVViewController alloc] init];
    //        [self.navigationController pushViewController:studyView animated:YES];
    //    }else{
    //        TVViewController *studyView = [[TVViewController alloc] init];
    //        [self.navigationController pushViewController:studyView animated:NO];
    //    }
}

////允许长按菜单
//-(BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath{
//    NSLog(@"xxx");
//    tableview_select_index = indexPath.row;
//    //    [tableview reloadData];
//    
//    UIActionSheet *sheet = nil;
//    if ([Global curLanguageEn]) {
//        sheet = [[UIActionSheet alloc] initWithTitle:@"Select" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Modify the device info", nil];
//        sheet.tag = modify_device_tag;
//        [sheet showInView:self.view];
//    }else{
//        sheet = [[UIActionSheet alloc] initWithTitle:@"选择操作" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"修改设备信息", nil];
//        sheet.tag = modify_device_tag;
//        [sheet showInView:self.view];
//    }
//    return NO;
//}
//-(BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender{
//    return NO;
//}
//-(BOOL)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender{
//    if (action==@selector(copy:)) {
//        return YES;
//    }
//    return NO;
//}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        DDAlertPrompt *loginPrompt = nil;
        if ([Global curLanguageEn]){
            loginPrompt = [[DDAlertPrompt alloc] initWithTitle:@"Input the device name" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitle:@"OK" content:@""];
            loginPrompt.tag = 23;
            [loginPrompt show];
        }else{
            loginPrompt = [[DDAlertPrompt alloc] initWithTitle:@"请输入设备名称" delegate:self cancelButtonTitle:@"取消" otherButtonTitle:@"确定" content:@""];
            loginPrompt.tag = 23;
            [loginPrompt show];
        }
    }
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex != [alertView cancelButtonIndex])
    {
        if (alertView.tag == 8889) {
            NSString *device_name = nil;
            if ([dicList allKeys].count > delete_index) {
                device_name = [[dicList allKeys] objectAtIndex:delete_index];
                [dicList removeObjectForKey:device_name];
            }
            [UD setObject:dicList forKey:LANIPAddress_list];
            [UD synchronize];
            
            [TableView1 reloadData];
        }else{
            DDAlertPrompt *loginPrompt = (DDAlertPrompt *)alertView;
            NSString *groupName = loginPrompt.plainTextField.text;
            if ([groupName length] > 0) {
                NSString *curDevice = [[dicList allKeys] objectAtIndex:tableview_select_index];
                
                NSDictionary *dicNameList = [UD objectForKey:LAN_Remote_Name_list];
                NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:dicNameList];
                [dic setObject:groupName forKey:curDevice];
                [UD setObject:dic forKey:LAN_Remote_Name_list];
                [UD synchronize];
                [TableView1 reloadData];
            }
        }
    }
}

@end
